class Album < ActiveRecord::Base
  has_many                :songs
  belongs_to              :artwork
  validates_presence_of   :name
  validates_presence_of   :year
  
  after_save              :associations_song_ids
  before_destroy          :set_album_songs_to_nil
  
  has_friendly_id         :name,            :use_slug => true
  
  def purchasable?
    self.purchase_link.nil? ? (return false) : (self.purchase_link.blank? ? (return false) : (return true))
  end
  
  def song_ids=(an_array_of_song_ids = [])
    @song_ids = an_array_of_song_ids
  end             
  
  def associations_song_ids
    Song.find(:all, :conditions => ['album_id = ?', self.id]).each do |song|
      song.album = nil
      song.save!
    end
    unless @song_ids.nil?
      @song_ids.each do |song_id|
        song = Song.find(song_id)
        song.album = self
        song.save!
      end
    end
  end

protected
  def set_album_songs_to_nil
    self.songs.each do |song|
      song.album = nil
      song.save!
    end
  end
end
